package com.example.prom.qianduoduo.y2025.handler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.example.prom.qianduoduo.y2025.model.MedicineInfo;
import com.example.prom.qianduoduo.y2025.model.MedicineInstruction;
import com.example.prom.qianduoduo.y2025.model.MedicineInfo;
import com.example.prom.strategy.excel.CustomCellStyleStrategy;
import com.example.prom.strategy.excel.CustomColumnWidthStrategy;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description
 *
 * @author DangWen
 */
public class YaozhMergeFileHandler {

//    public static void main(String[] args) {
//        // 从指定目录中读取所有 .xlsx 文件
//        File folder = new File("D:\\dangwen\\钱多多\\同事\\outputFiles\\");
//        File[] filesArray = folder.listFiles((dir, name) -> name.endsWith(".xlsx"));
//        List<String> files = new ArrayList<>();
//        if (filesArray != null) {
//            for (File file : filesArray) {
//                files.add(file.getAbsolutePath());
//            }
//        }
//
//        mergeExcelFiles(files, "D:\\dangwen\\钱多多\\同事\\mergedFile.xlsx");
//    }


    public static void mergeExcelFiles(List<String> sourceFiles, String targetFile) {

        // 用来收集所有文件的“两页”数据
        List<MedicineInfo> allMedicine          = new ArrayList<>();
        List<MedicineInstruction> allNoData     = new ArrayList<>();

        // 1. 先全部读完
        for (String file : sourceFiles) {
            readOneFile(file, allMedicine, allNoData);
        }

        // 2. 写出到新文件
        try (ExcelWriter writer = EasyExcel.write(targetFile)
                .registerWriteHandler(new CustomColumnWidthStrategy())
                .registerWriteHandler(new CustomCellStyleStrategy())
                .build()) {

            WriteSheet ws1 = EasyExcel.writerSheet("符合爬取条件的数据")
                    .head(MedicineInfo.class)
                    .build();
            WriteSheet ws2 = EasyExcel.writerSheet("不符合爬取条件的数据")
                    .head(MedicineInstruction.class)
                    .build();

            writer.write(allMedicine, ws1);
            writer.write(allNoData,   ws2);
        }

        System.out.printf("合并完成，共 %d 条有效药品数据，%d 条无数据记录 → %s%n",
                allMedicine.size(), allNoData.size(), targetFile);
    }

    /**
     * 读一个文件的两个 Sheet，并把过滤后的数据塞进两个全局 List
     */
    public static void readOneFile(String file,
                                    List<MedicineInfo> medicineList,
                                    List<MedicineInstruction> noDataList) {

        // ---------- Sheet1：符合爬取条件 ----------
        EasyExcel.read(file, MedicineInfo.class,
                        new PageReadListener<MedicineInfo>(page -> {
//                            page.removeIf(r ->
//                                    StringUtils.isBlank(r.getProductionEnterprise()) ||
//                                            r.getModificationDate() == null);
                            medicineList.addAll(page);
                        }))
                .sheet("符合爬取条件的数据")
                .doRead();

        // ---------- Sheet2：不符合爬取条件 ----------
        EasyExcel.read(file, MedicineInstruction.class,
                        new PageReadListener<MedicineInstruction>(noDataList::addAll))
                .sheet("不符合爬取条件的数据")
                .doRead();
    }


    private static List<MedicineInfo> readExcel(String filePath) {
        return EasyExcel.read(filePath)
                .head(MedicineInfo.class)
                .sheet()
                .doReadSync();
    }

    private static void writeExcel(List<MedicineInfo> data, String outputPath) {
        EasyExcel.write(outputPath, MedicineInfo.class)
                .sheet()
                .registerWriteHandler(new CustomColumnWidthStrategy())
                .registerWriteHandler(new CustomCellStyleStrategy())
                .doWrite(data);
        System.out.println("已生成差异文件：" + outputPath);
    }

    public static void main(String[] args) {
        List<MedicineInfo> result = new ArrayList<>();
        List<MedicineInfo> medicineList = new ArrayList<>();
        List<MedicineInstruction> noDataList = new ArrayList<>();
        readOneFile("D:\\dangwen\\钱多多\\同事\\mergedFile.xlsx", medicineList, noDataList);
        List<String> m1 = medicineList.stream().map(MedicineInfo::getMedicineName).collect(Collectors.toList());
        List<String> m2 = noDataList.stream().map(MedicineInstruction::getMedicineName).collect(Collectors.toList());
        m2.addAll(m1);
        List<MedicineInfo> MedicineInfos = readExcel("D:\\dangwen\\钱多多\\同事\\药品目录.xlsx");
        for (MedicineInfo medicineInfo : MedicineInfos) {
            if (!m2.contains(medicineInfo.getMedicineName())){
                result.add(medicineInfo);
            }
        }
        writeExcel(result, "D:\\dangwen\\钱多多\\同事\\被过滤未检索到药品的药物.xlsx");
    }
}
